package com.yunze.system.service.impl.yunze.bill;


import com.alibaba.fastjson.JSON;
import com.yunze.common.core.domain.entity.SysUser;
import com.yunze.common.mapper.mysql.YzExecutionTaskMapper;
import com.yunze.common.mapper.mysql.bill.YzBillMapper;
import com.yunze.common.mapper.mysql.bill.YzBillsMapper;
import com.yunze.common.utils.yunze.PageUtil;
import com.yunze.common.utils.yunze.VeDate;
import com.yunze.system.service.yunze.bill.IYzBillService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 账单 业务实现类
 *
 * @author root
 */
@Service
public class YzBillServiceImpl implements IYzBillService
{

    @Resource
    private YzBillMapper yzBillMapper;
    @Resource
    private YzBillsMapper yzBillsMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private YzExecutionTaskMapper yzExecutionTaskMapper;

    @Override
    public Map<String, Object> getList(Map<String, Object> map) {


        return null;
    }

    @Override
    public String exportBill(Map<String, Object> map, SysUser user) {
     return  null;

    }
    @Override
    public Map<String, Object> getListCopy(Map<String, Object> map) {
      return null;

    }

    public Map<String, Object> getListCopyZ(Map<String, Object> map) {
        Map<String, Object> omp = new HashMap<String, Object>();
        List<String> depts = new ArrayList<String>();
        PageUtil pu = null;
        /*判断 是否为总企业*/
        if (map.get("dept_id").equals("100")){
            depts = yzBillsMapper.selAlldept();
        }else{
            depts = yzBillsMapper.selDeptId(map);//查询所有子级企业dept
            depts.add(map.get("dept_id").toString());//放入自身dept_id
        }


        List<Map<String, Object>> RList = new ArrayList<>();//返回的datalist
        //HashMap<String, Object> RMap = new HashMap<>();//返回的map

        String fist_time = "";
        String end_time = "";
        if (map.get("month") == null || map.get("month") == ""){ //month -> 2023-06-29T16:00:00.000Z
        }else{
            fist_time= VeDate.getFistDayInMonthByDateCZC(map.get("month").toString()); // 获取 传过来的日期 的第一个 和最后一天
            end_time = VeDate.getLastDayInMonthByDateCZC(map.get("month").toString());

        }

        Integer currenPage = map.get("pageNum") != null ? Integer.parseInt(map.get("pageNum").toString()) : 0;
        Integer pageSize = map.get("pageSize") != null ? Integer.parseInt(map.get("pageSize").toString()) : 10;
        Integer rowCount = null;



        Map<String, Object> selMap = new HashMap<>();
        selMap.put("fist_time",fist_time);
        selMap.put("end_time",end_time);

        if (map.get("dname") == null || map.get("dname").equals("")){
            //没有输入 查询企业
            if (map.get("month") == null){
                // 也没有输入时间  查询全部

                rowCount = yzBillsMapper.selcountByDept(depts);
                rowCount = rowCount != null ? rowCount : 0;
                 pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                selMap.put("StarRow", pu.getStarRow());
                selMap.put("PageSize", pu.getPageSize());
                selMap.put("depts", depts);
                List<Map<String, Object>> billList = yzBillsMapper.selBillByDept(selMap);
                RList.addAll(billList);


            }else{
                selMap.put("depts", depts);
                rowCount =  yzBillsMapper.selcountByDeptAndMonth(selMap);
                rowCount = rowCount != null ? rowCount : 0;
                pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                selMap.put("StarRow", pu.getStarRow());
                selMap.put("PageSize", pu.getPageSize());
                List<Map<String, Object>> billList = yzBillsMapper.selBillByDeptAndMonth(selMap);

                RList.addAll(billList);


            }
        }else{
            String dname = map.get("dname").toString();
            String trim = dname.trim();
            selMap.put("dept_name",trim);//放入dept_name
            //输入了 查询企业
            if (map.get("month") == null){
                // 没有输入查询时间 查询所有的 deptname的bill
                //判断对应企业是否在 dept_id下 或 dept_id的子级下面
                //1.查询dept_name 所在 的dept_id
                try{
                    String deptId = yzBillsMapper.selDeptIdByDeptName(selMap.get("dept_name").toString()).get("dept_id").toString();//查询 输入的 dept_name 所在的 dept
                    if (deptId == null ||deptId == ""){ // 判断 输入的dept_name 是否存在
                    }else{
                        for (int i = 0; i < depts.size(); i++) {
                            if (depts.get(i).equals(deptId)){
                                //在 查询bill
                                rowCount = yzBillsMapper.selcountlByDeptName(selMap);
                                 pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                                selMap.put("StarRow", pu.getStarRow());
                                selMap.put("PageSize", pu.getPageSize());
                                selMap.put("depts", depts);
                                List<Map<String, Object>> billList = yzBillsMapper.selBillByDeptName(selMap);
                                RList.addAll(billList);

                                break;
                            }else{
                                //不在
                            }
                        }
                    }
                }catch(Exception e){

                }



            }else{

                String deptId = yzBillsMapper.selDeptIdByDeptName(selMap.get("dept_name").toString()).get("dept_id").toString();//查询 输入的 dept_name 所在的 dept
                if (deptId == null ||deptId == ""){ // 判断 输入的dept_name 是否存在
                }else{
                    for (int i = 0; i < depts.size(); i++) {

                        if (depts.get(i).equals(deptId)){
                            rowCount = yzBillsMapper.selcountByDeptNameAndMonth(selMap);
                             pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                            selMap.put("StarRow", pu.getStarRow());
                            selMap.put("PageSize", pu.getPageSize());
                            selMap.put("depts", depts);
                            //在 查询bill
                            List<Map<String, Object>> billList = yzBillsMapper.selBillByDeptNameAndMonth(selMap);

                            RList.addAll(billList);

                            break;
                        }else{
                            //不在
                        }
                    }
                }
            }
        }


        //数据打包

        omp.put("Pu", pu);
        HashMap<String, Object> mapo = new HashMap<>();
        //分组 table_packet 根据 tid
//        List<String> tIds = yzBillsMapper.selAllTid();
//        for (int i = 0; i <RList.size(); i++) {
//            String id = RList.get(i).get("id").toString();
//            if (tIds.indexOf(id) !=-1){
//                mapo.put("t_id",id);
//                List<Map<String, Object>> packetList = yzBillsMapper.selPacketMap(mapo);
//                RList.get(i).put("plist",packetList);
//            }
//        }
        for (int i = 0; i < RList.size(); i++) {
            RList.get(i).put("hasChildren",true);
        }
        omp.put("Data",RList);
        return omp;
    }
    @Override
    public String exportBillCopy(Map<String, Object> map, SysUser user) {
        Map<String, Object> omp = new HashMap<String, Object>();
        //判断 时间 moth在那个月  {"pageNum":1,"pageSize":10,"month":null,"package_id":null,"dept_id:100"}
        String fist_time = "";
        String end_time = "";
        if (map.get("month") == null || map.get("month") == ""){ //month -> 2023-06-29T16:00:00.000Z
//           fist_time=  VeDate.getNowMonthFistDayCZC();
//           end_time =  VeDate.getNowMonthLastDayCZC();
        }else{
            fist_time= VeDate.getFistDayInMonthByDateCZC(map.get("month").toString()); // 获取 传过来的日期 的第一个 和最后一天
            end_time = VeDate.getLastDayInMonthByDateCZC(map.get("month").toString());

        }
        map.put("fist_time",fist_time);
        map.put("end_time",end_time);
        Integer currenPage = map.get("pageNum") != null ? Integer.parseInt(map.get("pageNum").toString()) : 0;
        Integer pageSize = map.get("pageSize") != null ? Integer.parseInt(map.get("pageSize").toString()) : 10;
        Integer rowCount = null;
        PageUtil pu = null;
        List<Map<String, Object>> outList =new ArrayList<Map<String,Object>>();
        List<String> depts = yzBillsMapper.selDeptId(map);//查询所有子级企业dept
        depts.add(map.get("dept_id").toString());//放入自身dept_id
        Map<String, Object> selMap = new HashMap<>();
        selMap.put("fist_time",fist_time);
        selMap.put("end_time",end_time);

        if (map.get("dname") == null || map.get("dname").equals("")){
            //没有输入 查询企业
            if (map.get("month") == null){
                // 也没有输入时间  查询全部

                rowCount = yzBillsMapper.selcountByDept(depts);
                rowCount = rowCount != null ? rowCount : 0;
                pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                selMap.put("StarRow", pu.getStarRow());
                selMap.put("PageSize", pu.getPageSize());
                selMap.put("depts", depts);
                List<Map<String, Object>> billList = yzBillsMapper.selBillByDept(selMap);
                outList.addAll(billList);


            }else{
                rowCount =  yzBillsMapper.selcountByDeptAndMonth(selMap);
                rowCount = rowCount != null ? rowCount : 0;
                pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                selMap.put("StarRow", pu.getStarRow());
                selMap.put("PageSize", pu.getPageSize());
                selMap.put("depts", depts);
                List<Map<String, Object>> billList = yzBillsMapper.selBillByDeptAndMonth(selMap);

                outList.addAll(billList);


            }
        }else{
            selMap.put("dept_name",map.get("dname"));//放入dept_name
            //输入了 查询企业
            if (map.get("month") == null){
                // 没有输入查询时间 查询所有的 deptname的bill
                //判断对应企业是否在 dept_id下 或 dept_id的子级下面
                //1.查询dept_name 所在 的dept_id
                try{
                    String deptId = yzBillsMapper.selDeptIdByDeptName(selMap.get("dept_name").toString()).get("dept_id").toString();//查询 输入的 dept_name 所在的 dept
                    if (deptId == null ||deptId == ""){ // 判断 输入的dept_name 是否存在
                    }else{
                        for (int i = 0; i < depts.size(); i++) {
                            if (depts.get(i).equals(deptId)){
                                //在 查询bill
                                rowCount = yzBillsMapper.selcountlByDeptName(selMap);
                                pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                                selMap.put("StarRow", pu.getStarRow());
                                selMap.put("PageSize", pu.getPageSize());
                                selMap.put("depts", depts);
                                List<Map<String, Object>> billList = yzBillsMapper.selBillByDeptName(selMap);
                                outList.addAll(billList);

                                break;
                            }else{
                                //不在
                            }
                        }
                    }
                }catch(Exception e){

                }



            }else{

                String deptId = yzBillsMapper.selDeptIdByDeptName(selMap.get("dept_name").toString()).get("dept_id").toString();//查询 输入的 dept_name 所在的 dept
                if (deptId == null ||deptId == ""){ // 判断 输入的dept_name 是否存在
                }else{
                    for (int i = 0; i < depts.size(); i++) {

                        if (depts.get(i).equals(deptId)){
                            rowCount = yzBillsMapper.selcountByDeptNameAndMonth(selMap);
                            pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
                            selMap.put("StarRow", pu.getStarRow());
                            selMap.put("PageSize", pu.getPageSize());
                            selMap.put("depts", depts);
                            //在 查询bill
                            List<Map<String, Object>> billList = yzBillsMapper.selBillByDeptNameAndMonth(selMap);

                            outList.addAll(billList);

                            break;
                        }else{
                            //不在
                        }
                    }
                }
            }
        }


        HashMap<String, Object> mapo = new HashMap<>();
        for (int i = 0; i < outList.size(); i++) {
            String id = outList.get(i).get("id").toString();
            mapo.put("t_id",id);
            List<Map<String, Object>> packetList = yzBillsMapper.selPacketMap(mapo);
            outList.get(i).put("plist",packetList);

        }


        Map<String, Object> oMap = new HashMap<>();
        String create_by = " [ " + user.getDept().getDeptName() + " ] - " + " [ " + user.getUserName() + " ] ";
        String newName = UUID.randomUUID().toString().replace("-", "") + "_BillOut.xlsx";

        String agent_id = user.getDept().getDeptId().toString();
        String task_name = "-物联网账单 [导出] ";
        String SaveUrl = "/getcsv/" + newName;
        //String SaveUrl = "/mnt/yunze/download/csv/" + newName;
        //File file = new File(SaveUrl);


        oMap.put("auth",create_by);
        oMap.put("task_name",task_name);
        oMap.put("url", SaveUrl);
        //oMap.put("url", file.getAbsolutePath());
        oMap.put("type", 46);
        oMap.put("agent_id", agent_id);
        oMap.put("OutList", outList);
        oMap.put("newName", newName);

        String polling_queueName =  "admin_exportBill_queue";
        String polling_routingKey = "admin.exportBill.queue";
        String polling_exchangeName = "admin_exchange";//路由

        try{
//            rabbitTemplate.convertAndSend(polling_queueName, polling_routingKey, JSON.toJSONString(oMap), message -> {
//                // 设置消息过期时间 30 分钟 过期
//                message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
//                return message;
//            });

            int id = yzExecutionTaskMapper.add(oMap);//添加到执行任务
            rabbitTemplate.convertAndSend(polling_exchangeName, polling_routingKey, JSON.toJSONString(oMap), message -> {
                // 设置消息过期时间 30 分钟 过期
                message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
                return message;
            });

            return "已下发执行日志可在【系统管理】》【日志管理】》【执行日志】查看";
        }catch (Exception e){
            return "物联网卡账单导出错误!";
        }



    }

    @Override
    public Map<String,Object> plist(Map<String, Object> map) {
        Map<String, Object> rMap = new HashMap<>();
        List<Map<String, Object>> plist = yzBillsMapper.getPlist(map);
        rMap.put("data",plist);
        return rMap;
    }
}





























